# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.

from odoo import api, fields, models, _
from odoo.exceptions import UserError, ValidationError


class ResCompany(models.Model):
    _inherit = "res.company"

    def _get_fp_partner(self):
        return self.env['fp.partner'].search(
            [('draw_company_id', '=', self.id)], limit=1)


class FapiaoPartner(models.Model):
    _name = "fp.partner"
    _description = "Fapiao Partner"
    _order = 'code'

    be_customer = fields.Boolean(default=True)
    be_supplier = fields.Boolean(default=False)
    be_draw_company = fields.Boolean(default=False)

    draw_company_id = fields.Many2one(
        'res.company', 'Invoice Company', ondelete='restrict',
        help='开票时, 作为销售方公司')

    partner_id = fields.Many2one(
        'res.partner', string='Partner', required=True, index=True, ondelete='restrict')

    active = fields.Boolean(related='partner_id.active', store=True)

    name = fields.Char(
        string='Name', related='partner_id.name', required=True,  store=True, readonly=False)
    fapiao_name = fields.Char(
        string='Fapiao Name', required=True,  store=True, readonly=False, help="票面信息")
    shortname = fields.Char(string='shortname', required=True)

    code = fields.Char(
        string='Code', related='partner_id.ref', store=True, readonly=False)
    tin = fields.Char(
        string='TIN', related='partner_id.vat', store=True, readonly=False,
        help="Tax Identification Number 票面信息")
    phone = fields.Char(
        string='Phone', related='partner_id.phone', store=True, readonly=False, help="票面信息")
    address = fields.Char(string='Address', help="票面信息")

    partner_bank_id = fields.Many2one(
        'res.partner.bank', string='Partner Bank', domain="[('partner_id', '=?', partner_id)]")

    bank_id = fields.Many2one(
        'res.bank', string='Bank', related='partner_bank_id.bank_id')

    bank_name = fields.Char(string='Bank Name', help="票面信息")
    acc_number = fields.Char(string='Account Number', help="票面信息")

    address_phone = fields.Char(
        string='Address Phone', compute='_compute_address_phone', store=True)
    bank_account = fields.Char(
        string='Bank Account', compute='_compute_bank_account', store=True)

    address_phone2 = fields.Char(string='Address Phone 2', help="进项票票面信息")
    bank_account2 = fields.Char(string='Bank Account 2', help="进项票票面信息")

    @api.constrains('draw_company_id')
    def _check_draw_company_id(self):
        for one in self:
            if one.draw_company_id:
                all_ins = self.search(
                    [('draw_company_id', '=', one.draw_company_id.id)])
                if len(all_ins.ids) > 1:
                    raise ValidationError(
                        _('One Company (%s) cannot be set two times', one.draw_company_id.name))

    @api.depends('address', 'phone', 'address_phone2')
    def _compute_address_phone(self):
        for rec in self:
            if rec.address and rec.phone:
                rec.address_phone = rec.address + ' ' + rec.phone
            elif rec.address_phone2:
                rec.address_phone = rec.address_phone2
            else:
                rec.address_phone = rec.address or rec.phone or ''

    @api.depends('bank_name', 'acc_number', 'bank_account2')
    def _compute_bank_account(self):
        for rec in self:
            if rec.bank_name and rec.acc_number:
                rec.bank_account = rec.bank_name + ' ' + rec.acc_number
            elif rec.bank_account2:
                rec.bank_account = rec.bank_account2
            else:
                rec.bank_account = rec.bank_name or rec.acc_number or ''

    @api.onchange('partner_id')
    def on_change_partner_id(self):
        for one in self:
            one.partner_bank_id = False
            one.bank_name = False
            one.acc_number = False

    # @api.onchange('bank_name', 'acc_number')
    # def on_change_bank_name_and_acc(self):
    #     for one in self:
    #         if one.bank_name and one.acc_number:
    #             bank_id = self.env['res.bank'].search(
    #                 [('name', '=', one.bank_name)], limit=1)
    #             if not bank_id:
    #                 bank_id = self.env['res.bank'].create(
    #                     {'name': one.bank_name})

    #             bank_vals = {
    #                 'bank_id': bank_id.id,
    #                 'partner_id': one.id,
    #                 'acc_number': one.acc_number}

    #             if one.partner_bank_id:
    #                 one.partner_bank_id.write(bank_vals)

    #             else:
    #                 one.partner_bank_id = self.env['res.partner.bank'].create(
    #                     bank_vals)

    #         else:
    #             one.partner_bank_id = False

    @api.model_create_multi
    def create(self, vals_list):
        # create missing partners
        no_partner_vals_list = [
            vals
            for vals in vals_list
            if vals.get('name') and not vals.get('partner_id')
        ]

        if no_partner_vals_list:
            partners = self.env['res.partner'].create([
                {
                    'is_company': True,
                    'name': vals['name'],
                    'ref': vals.get('code'),
                    'vat': vals.get('tin'),
                    'phone': vals.get('phone'),
                }
                for vals in no_partner_vals_list
            ])
            # compute stored fields, for example address dependent fields
            partners.flush_model()

            for vals, partner in zip(no_partner_vals_list, partners):
                vals['partner_id'] = partner.id
                if not vals.get('shortname'):
                    vals['shortname'] = partner.name
                if not vals.get('fapiao_name'):
                    vals['fapiao_name'] = partner.name

        for vals in vals_list:
            if not vals.get('shortname'):
                vals['shortname'] = vals['name']
            if not vals.get('fapiao_name'):
                vals['fapiao_name'] = vals['name']

        self.clear_caches()
        fp_partners = super().create(vals_list)

        return fp_partners

    # unlink todo 删除 res.partner

    @api.model
    def lookup_for_in(self, values):
        fapiao_name = values['fapiao_name']
        tin = values['tin']
        address_phone = values['address_phone']
        bank_account = values['bank_account']

        if tin:
            domain = [('tin', '=', tin)]
        else:
            domain = [('fapiao_name', '=', fapiao_name)]

        partner = self.search(domain, limit=1)
        if not partner.be_supplier:
            partner.be_supplier = True

        if not partner:
            partner = self.create({
                'name': fapiao_name,
                'tin': tin,
                'address_phone2': address_phone,
                'bank_account2': bank_account,
                'be_supplier': True,
                'be_customer': False
            })

        return partner
